﻿using System;
using System.IdentityModel.Tokens;
using System.Collections.ObjectModel;
using SecurityTokenServiceNS;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.Xml;

namespace IssuedTokenAddIns
{
	public class IssuedTokenModuleOpenID : IIssuedTokenProcessor
	{
		/// <summary>
		/// This method generates the Token to be issued
		/// </summary>
		/// <param name="stsName">Name of the Issuer</param>
		/// <param name="proof">Proof Token</param>
		/// <param name="claims">Claims</param>
		/// <param name="rstr">RSTR</param>
		public void GenerateIssuedToken(string stsName, SecurityKeyIdentifier proof, 
			Collection<Claim> claims, RSTR rstr)
		{
			if (rstr.RST.TokenType != Constants.OpenID.NamespaceUri)
				return;

			XmlDocument doc = new XmlDocument();
			XmlElement tokendata = doc.CreateElement(Constants.OpenID.Prefix, Constants.OpenID.OpenIDToken, Constants.OpenID.NamespaceUri);

			tokendata.InnerText = "\n";
			foreach(Claim claim in claims)
				tokendata.InnerText += Constants.OpenID.Prefix+'.'+claim.ClaimType+':'+claim.Resource+"\n";

			X509SecurityToken issuerToken = (X509SecurityToken)StsConfiguration.Current.GetStsToken();
			SecurityKeyIdentifierClause clause = issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
			GenericXmlSecurityToken openidToken = new GenericXmlSecurityToken(tokendata, null,
				DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1), clause, clause, null);
			rstr.RequestedSecurityToken = openidToken;
			rstr.RequestedAttachedReference = openidToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
			rstr.RequestedUnattachedReference = openidToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
		}
	}
}
